const { app, BrowserWindow, Menu, Tray, ipcMain, globalShortcut, dialog, safeStorage, protocol } = require('electron')
const storage = require('electron-localstorage');
const path = require('path')
const iconPath = path.join(__dirname, 'static/icons/logo.png')

//创建全局窗口变量，全局系统托盘变量(全局变量防止变量回收托盘自动消失)
let mainWindow, MyTray
//创建登录窗口
const createLoginWindow = () => {
    mainWindow = new BrowserWindow({
        minWidth: 1200,
        minHeight: 800,
        width: 1720,
        height: 800,
        sandbox: true,
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false, //这两步结合，开启渲染进程中使用
            webviewTag: true,
        },
        icon: iconPath, //设置左上角以及主图标
    })
    Menu.setApplicationMenu(null) //禁用顶部菜单
    globalShortcut.unregisterAll()
    shortCut()
    setWin()
    mainWindow.loadURL('http://192.168.0.125/')
}

//响应最小化、最大化以及关闭按钮
function setWin() {
    ipcMain.on('minimize', () => mainWindow.minimize());
    ipcMain.on('maximize', () => {
        if (mainWindow.isMaximized()) {
            mainWindow.restore();
        } else {
            mainWindow.maximize()
        }
    });
    ipcMain.on('close', () => mainWindow.close());
}

//系统托盘
function tray() {
    MyTray = new Tray(iconPath)
    const contextMenu = Menu.buildFromTemplate([
        { label: '主程序', role: 'mainWindow', click: () => { mainWindow.show() } },
        {
            label: '清除缓存', role: 'clearCache', click: () => {
                showConfirmationDialog('确认清除缓存并且重新登录？', (flag) => {
                    if (flag) {
                        const { session } = mainWindow.webContents
                        session.clearStorageData()
                        session.clearCache()
                        session.clearCodeCaches([])
                        session.clearHostResolverCache()
                        session.clearAuthCache()
                        mainWindow.focus()
                        mainWindow.reload()
                    }
                })
            }
        },
        { label: '最小化', role: 'minimize', click: () => { mainWindow.minimize() } },
        { label: '退出', role: 'quit', click: () => { app.quit() } }
    ])

    MyTray.setToolTip('双马系统\nv2.8.0')
    MyTray.setTitle('This is my title')
    //设置右键菜单，可以使用MyTray.setContextMenu(contextMenu)
    MyTray.on('right-click', () => {
        MyTray.popUpContextMenu(contextMenu)
    })
    //设置左键点击显示窗口
    MyTray.on('click', (e, bounds) => {
        mainWindow.show()
    })
}

//右键菜单
function rightClickMenu() {
    const contextMenu = Menu.buildFromTemplate([
        { label: '复制', role: 'copy', click: () => { } },
        { label: '粘贴', role: 'paste', click: () => { } },
    ])

    // 监听右键菜单事件
    mainWindow.webContents.on('context-menu', (event, params) => {
        contextMenu.popup(mainWindow, params.x, params.y)
    })
}

//窗口快捷键
function shortCut() {
    //F5刷新
    globalShortcut.register('F5', () => {
        if (mainWindow.isFocused()) mainWindow.reload()
    })
    //F10最小化
    globalShortcut.register('F10', () => {
        if (mainWindow.isFocused()) mainWindow.minimize()
    })
    //F11全屏与恢复
    globalShortcut.register('F11', () => {
        if (mainWindow.isFocused()) {
            if (mainWindow.isMaximized() || mainWindow.isFullScreen()) {
                mainWindow.setFullScreen(false)
                mainWindow.restore()
            } else {
                mainWindow.setFullScreen(true)//全屏无边框
                mainWindow.maximize()
            }
        }
    })
    //设置缩放，重置
    globalShortcut.register('ctrl+0', () => {
        mainWindow.webContents.setZoomFactor(1)
        storage.setItem("zoomFactor", 1)
    })
    globalShortcut.register('ctrl+-', () => {
        const zoomFactor = storage.getItem("zoomFactor") || 1
        if (zoomFactor > 0.4) {
            mainWindow.webContents.setZoomFactor(zoomFactor - 0.1)
            storage.setItem("zoomFactor", zoomFactor - 0.1)
        }
    })
    globalShortcut.register('ctrl+=', () => {
        const zoomFactor = storage.getItem("zoomFactor") || 1
        if (zoomFactor < 3) {
            mainWindow.webContents.setZoomFactor(zoomFactor + 0.1)
            storage.setItem("zoomFactor", zoomFactor + 0.1)
        }
    })
    //监听鼠标滚轮
    mainWindow.webContents.on('zoom-changed', (event, zoomDirection) => {
        if (zoomDirection === 'in') {
            const zoomFactor = storage.getItem("zoomFactor") || 1
            if (zoomFactor < 3) {
                mainWindow.webContents.setZoomFactor(zoomFactor + 0.1)
                storage.setItem("zoomFactor", zoomFactor + 0.1)
            }
        } else {
            const zoomFactor = storage.getItem("zoomFactor") || 1
            if (zoomFactor > 0.4) {
                mainWindow.webContents.setZoomFactor(zoomFactor - 0.1)
                storage.setItem("zoomFactor", zoomFactor - 0.1)
            }
        }
    })
}

const gotTheLock = app.requestSingleInstanceLock()
if (!gotTheLock) {
    app.quit()
} else {
    app.on('second-instance', (event) => {
        if (mainWindow) {
            if (mainWindow.isMinimized()) mainWindow.restore()
            mainWindow.focus()
        }
    })
    protocol.registerSchemesAsPrivileged([
        {
            scheme: 'http',
            privileges: {
                bypassCSP: true,
                secure: true,
                supportFetchAPI: true,
                corsEnabled: true
            }
        }
    ]);
    app.on('ready', () => {
        createLoginWindow()
        tray()
        rightClickMenu()
    })
}

//监听窗口关闭的事件，关闭的时候退出应用，macOS需要排除
app.on('window-all-closed', () => {
    console.log(process.platform);
    if (process.platform !== 'darwin') {
        app.quit()
    }
})

function showConfirmationDialog(message, callback) {
    const options = {
        type: 'question',
        buttons: ['取消', '确认'],
        defaultId: 1,
        title: '确认操作',
        message: message,
        cancelId: 0
    };

    dialog.showMessageBox(null, options).then(({ response }) => {
        console.log(response);
        // response为用户选择的按钮索引：0表示取消，1表示确认
        callback(response === 1); // 将true或false传递给回调函数
    })
}
